package com.grgbanking.it.wx.common.creator;

import org.springframework.beans.factory.annotation.Autowired;

import net.sf.json.JSONObject;

import com.grgbanking.it.common.HttpConnection;
import com.grgbanking.it.common.json.JSONConfigUtil;
import com.grgbanking.it.common.util.XMLUtil;
import com.grgbanking.it.wx.aes.AesException;
import com.grgbanking.it.wx.common.Token;
import com.grgbanking.it.wx.common.WXConstant;
import com.grgbanking.it.wx.entity.WXMessage;
import com.grgbanking.it.wx.entity.WXPassiveMessage;
import com.grgbanking.it.wx.entity.WXTextMessage;
import com.grgbanking.it.wx.entity.WXVerify;

/**
 * 微信信息处理对象基类
 * 信息的接收及发送
 * 信息的加密及解密
 * 
 * WXBaseMessageCreator
 * 
 * @author 潘广伟
 * @Email p_3er@qq.com
 * @Date 2015-1-7 下午4:51:51
 * 
 * @version 1.0.0
 *
 */
public abstract class WXBaseMessageCreator {
	@Autowired
	protected HttpConnection httpConnection;
	protected Integer agentId;
	
	public WXPassiveMessage createPassiveMessage() {
		return new WXPassiveMessage(agentId);
	}
	
	public WXMessage createMessage() {
		return new WXMessage(agentId);
	}
	
	/**
	 * 给用户发送微信
	 * sentMessageToUser
	 * 
	 * @param user
	 * @param text
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public String sentMessageToUser(String user,String text) throws Exception{
		WXMessage message = createMessage();
		message.setTouser(user);
		message.setMsgtype("text");
		message.setText(new WXTextMessage(text));
		return sendJSONMessage(message);
	}
	
	/**
	 * JSON格式微信发送
	 * sendMessage
	 * 
	 * @param message
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public String sendJSONMessage(WXMessage message) throws Exception{
		StringBuffer url = new StringBuffer(WXConstant.MESSAGE_SENT_URL).append(Token.getToken(httpConnection));
		String content = JSONObject.fromObject(message,JSONConfigUtil.getNotEmptyConfig()).toString();
		
		String callback = httpConnection.sendPost(url.toString(), content);
		
		return callback;
	}

	
	/**
	 * 加密回复的信息
	 * encryptMsg
	 * 
	 * @param msg  xml信息
	 * @param verify
	 * @return 
	 * @throws AesException 
	 * @exception 
	 * @since  1.0.0
	 */
	protected String encryptMsg(String msg,String timestamp,String nonce) throws AesException{
		return WXBizMsgCryptFactory.getCrypt(agentId).EncryptMsg(msg, timestamp, nonce);
	}
	

	
	
	//测试
	@Deprecated
	protected String processDecryptMsg(String msg) {
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常，请稍候尝试！";

			WXPassiveMessage recivedMessage = this.reciveMessage(msg);
			
			
			// 回复文本消息
//			TextMessage textMessage = new TextMessage();
//			textMessage.setToUserName(fromUserName);
//			textMessage.setFromUserName(toUserName);
//			textMessage.setCreateTime(new Date().getTime());
//			textMessage.setMsgType(WXConstant.RESP_MESSAGE_TYPE_TEXT);
//			textMessage.setFuncFlag(0);
			
			// 文本消息
			if (recivedMessage.getMsgType().equals(WXConstant.REQ_MESSAGE_TYPE_TEXT)) {
				String content = recivedMessage.getContent(); 
				
				respContent = "Sunlight提示：您发送的是文本消息！内容是："+content;
			}
			// 图片消息
			else if (recivedMessage.getMsgType().equals(WXConstant.REQ_MESSAGE_TYPE_IMAGE)) {
				String picUrl = recivedMessage.getPicUrl(); 
				respContent = "Sunlight提示：您发送的是图片消息！";
			}
			// 地理位置消息
			else if (recivedMessage.getMsgType().equals(WXConstant.REQ_MESSAGE_TYPE_LOCATION)) {
				respContent = "Sunlight提示：您发送的是地理位置消息！"; 
			}
			// 链接消息
			else if (recivedMessage.getMsgType().equals(WXConstant.REQ_MESSAGE_TYPE_LINK)) {
				respContent = "Sunlight提示：您发送的是链接消息！";
			}
			// 音频消息
			else if (recivedMessage.getMsgType().equals(WXConstant.REQ_MESSAGE_TYPE_VOICE)) {
				respContent = "Sunlight提示：您发送的是音频消息！";
			}
			// 事件推送
//			else if (recivedMessage.getMsgType().equals(WXConstant.REQ_MESSAGE_TYPE_EVENT)) {
//				// 事件类型
//				String eventType = recivedMessage.getMsgType().get("Event");
//				// 自定义菜单点击事件
//				if (eventType.equalsIgnoreCase(WXConstant.EVENT_TYPE_CLICK)) {
//					// 事件KEY值，与创建自定义菜单时指定的KEY值对应  
//                    String eventKey = xmlMap.get("EventKey");	
//                    System.out.println("EventKey="+eventKey);
//                    respContent = "Sunlight提示：您点击的菜单KEY是"+eventKey;
//				}
//			}

//			textMessage.setContent(respContent);
//			respMessage = WXConstant.textMessageToXml(textMessage);
		} catch (Exception e) {
			e.printStackTrace();
			respMessage="有异常了。。。";
		}
		return respMessage;
	}
	
	/**
	 * 接收到的信息
	 * reciveMessage
	 * 
	 * @param verify
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	public WXPassiveMessage reciveMessage(WXVerify verify) throws Exception{
		String msg = this.getDecryptMsg(verify);
		return new WXPassiveMessage(XMLUtil.parseXml(msg));
	}
	
	/**
	 * 接收到的信息
	 * reciveMessage
	 * 
	 * @param msg
	 * @return
	 * @throws Exception 
	 * @exception 
	 * @since  1.0.0
	 */
	protected WXPassiveMessage reciveMessage(String msg) throws Exception{
		return new WXPassiveMessage(XMLUtil.parseXml(msg));
	}
	
	/**
	 * 获取回调的明文
	 * getEcho
	 * 
	 * @param msg_signature
	 * @param timestamp
	 * @param nonce
	 * @param echostr
	 * @return
	 * @throws AesException 
	 * @exception 
	 * @since  1.0.0
	 */
	public String getEcho(WXVerify verify) throws AesException{
		return WXBizMsgCryptFactory.getCrypt(agentId).VerifyURL(verify.getMsg_signature(), verify.getTimestamp(), verify.getNonce(), verify.getEchostr());
	}
	
	/**
	 * 获取POST过来的明文
	 * getDecryptMsg
	 * 
	 * @param verify
	 * @return
	 * @throws AesException 
	 * @exception 
	 * @since  1.0.0
	 */
	protected String getDecryptMsg(WXVerify verify) throws AesException{
		return WXBizMsgCryptFactory.getCrypt(agentId).DecryptMsg(verify.getMsg_signature(), verify.getTimestamp(), verify.getNonce(), verify.getPostData());
	}
	
	/**
	 * 文本消息对象转换成xml
	 * 
	 * @param textMessage
	 *            文本消息对象
	 * @return xml
	 */
	protected  String textMessageToXml(WXPassiveMessage message) {
		XMLUtil.getXstream().alias("xml", message.getClass());
		return XMLUtil.getXstream().toXML(message);
	}
}
